package com.ruoyi.tester.login;

import com.mashape.unirest.http.Headers;
import com.mashape.unirest.http.HttpResponse;
import com.ruoyi.tester.domain.TesterLoginConfig;
import com.ruoyi.tester.domain.TesterLoginRst;
import com.ruoyi.tester.executor.InterfaceCallUtils;
import com.ruoyi.tester.executor.http.HttpUtils;
import com.ruoyi.tester.executor.http.HttpUtilsFactory;
import com.ruoyi.tester.executor.http.XzfHttpResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author SongJun
 * @description TODO:
 * @date 2022/4/22 10:31
 */
@Component
public class XzfLogin implements Login {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public String getLoginType() {
        return "XZF";
    }

    @Override
    public TesterLoginRst doLogin(Long loginConfigId) {
        TesterLoginConfig loginBaseInfo = LoginCache.getLoginBaseInfo(loginConfigId);
        String loginParam = loginBaseInfo.getLoginParam();
        logger.info("小钻风登录参数,loginUrl={}, loginParam={}", loginBaseInfo.getLoginUrl(), loginParam);
        HttpUtils httpUtils = HttpUtilsFactory.getHttpUtils();
        XzfHttpResult xzfHttpResult = httpUtils.post(loginBaseInfo.getLoginUrl(), "application/x-www-form-urlencoded; charset=UTF-8", null, null, loginParam, null);
        Map<String, String> headers = xzfHttpResult.getHeaders();
        logger.info("小钻风登录结果headers={}", headers);
        String cookies = headers.get("Set-Cookie");
        if(StringUtils.hasLength(cookies)){
            int pos = cookies.indexOf(";");
            String cookie = cookies.substring(0, pos);
            TesterLoginRst loginRst = new TesterLoginRst(cookie, System.currentTimeMillis(), loginBaseInfo);
            return loginRst;
        }
        return null;
    }

    @Override
    public Map<String, String> makeHeaders(Long loginConfigId) {
        Map<String, String> headers = new HashMap<>();
        if(loginConfigId != null){
            TesterLoginRst cache = LoginCache.getCache(loginConfigId);
            if(cache != null){
                String cookie = (String)cache.getLoginResponse();
                headers.put("Cookie", cookie);
            }
        }
        return headers;
    }
}
